package com.ls.netty.http;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

import java.net.SocketAddress;
import java.net.URI;


/**
 * SimpleChannelInboundHandler 是ChannelInboundHandlerAdapter的子类
 */
public class TestHttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {

    //读取客户端数据
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {

        //判断msg是不是httpRequest请求
        if (msg instanceof HttpRequest) {

            SocketAddress remoteAddress = ctx.channel().remoteAddress();
            System.out.println("client address is " + remoteAddress);


            HttpRequest httpRequest = (HttpRequest) msg;
            URI uri = new URI(httpRequest.uri());
            if ("/favicon.ioc".equals(uri.getPath())) {
                System.out.println("favicon");
                return;
            }


            ByteBuf content = Unpooled.copiedBuffer("hello i am server 嘿嘿", CharsetUtil.UTF_8);

            FullHttpResponse response
                    = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, content);
            response.headers().set(HttpHeaderNames.CONTENT_TYPE,"application/json");
//            response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain");//响应类型文本
            response.headers().set(HttpHeaderNames.CONTENT_ENCODING, CharsetUtil.UTF_8);
            response.headers().set(HttpHeaderNames.CONTENT_LENGTH, content.readableBytes());



            ctx.writeAndFlush(response);
            System.out.println("ok");
        }


    }



}
